<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\Pc\WalmartApiController;
use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;


class Fpx extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:fpx {fun} {p1?}';


    /**
     * fpx
     *
     * @var string
     */
    protected $description = 'fpx';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $type = $this->argument('fun');

        switch ($type) {
            case 'walmartShipping':
                //沃尔玛物流单号回填
                $this->walmartShipping();
                break;
            default:
                exit('未知参数,程序结束');
        }

    }


    //沃尔玛物流单号回填
    public function walmartShipping()
    {
        $autoShipmentLogList = DB::table('auto_shipments_log')
            ->where('type', 2)//沃尔玛
            ->where('status', 3)//待回填物流单号
            ->get();


        foreach ($autoShipmentLogList as $autoShipmentLog) {
            $logisticsChannelNo = DB::table('fpx_order')
                ->where('order_id', $autoShipmentLog->order_id)
                ->where('shop_id', $autoShipmentLog->shop_id)
                ->where('type', 2)
                ->where('status', '>=', 0)
                ->value('logistics_channel_no');

            if (!$logisticsChannelNo) continue;

            //物流渠道号码 不是42开头，不回填物流单号
            $match = substr($logisticsChannelNo, 0, 2);
            if ($match != '42') continue;

            //沃尔玛物流单号回填
            $res = $this->walmartShippingFun($autoShipmentLog->local_order_id, $logisticsChannelNo);

            //更新批量发货日志
            DB::table('auto_shipments_log')->where('id', $autoShipmentLog->id)->update([
                'status' => $res['status'],
                'msg'    => $res['msg'],
            ]);
        }


    }

    //沃尔玛物流单号回填
    public function walmartShippingFun($id, $logisticsChannelNo)
    {
        $orderItemList = DB::table('walmart_order_item')
            ->select(['id', 'shop_id', 'purchase_order_id', 'line_number', 'order_line_quantity_amount'])
            ->where('walmart_order_id', $id)
            ->get();


        $orderId = $orderItemList[0]->purchase_order_id;

        $orderLines = [];
        foreach ($orderItemList as $orderItem) {
            $orderLines['orderLine'][] = [
                'lineNumber'        => $orderItem->line_number,
                'sellerOrderId'     => $orderItem->purchase_order_id,
                'orderLineStatuses' => [
                    'orderLineStatus' => [
                        [
                            'status'         => 'Shipped',
                            'statusQuantity' => [
                                'unitOfMeasurement' => 'EACH',
                                'amount'            => $orderItem->order_line_quantity_amount,//数量
                            ],
                            'trackingInfo'   => [
                                'shipDateTime'   => time() * 1000,
                                'carrierName'    => ['carrier' => '4PX'],
                                'methodCode'     => 'Standard',
                                'trackingNumber' => $logisticsChannelNo,
                            ],
                        ]
                    ]
                ],
            ];
        }

        $params = ['orderShipment' => ['orderLines' => $orderLines]];

        $shop = (new BaseModel())->GetShop($orderItemList[0]->shop_id);

        $accessToken = json_decode($shop['access_token'], true);
        $walmart     = new WalmartApiController($shop['Id'], $accessToken['client_id'], $accessToken['client_secret']);

        $result = $walmart->walmartApi('post', "/v3/orders/$orderId/shipping", $params);

        if (is_null($result) || isset($result['errors'])) {
            $msg = '';
            isset($result['errors']) && $msg = json_encode($result, JSON_UNESCAPED_UNICODE);
            return ['status' => 2, 'msg' => $msg];
        }

        return ['status' => 1, 'msg' => ''];
    }

}
